package com.ruicar.afs.cloud.channel.online.controller;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ruicar.afs.cloud.channel.common.feign.ChannelUseCaseService;
import com.ruicar.afs.cloud.channel.common.until.ChannelConfig;
import com.ruicar.afs.cloud.channel.online.condition.QuotaCondition;
import com.ruicar.afs.cloud.channel.online.entity.ChannelQuotaInfoTemp;
import com.ruicar.afs.cloud.channel.online.entity.ChannelRiskInfoTemp;
import com.ruicar.afs.cloud.channel.online.service.ChannelQuotaInfoService;
import com.ruicar.afs.cloud.channel.online.service.ChannelRiskInfoService;
import com.ruicar.afs.cloud.channel.online.vo.ChannelQuotaInfoVo;
import com.ruicar.afs.cloud.common.core.util.IResponse;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@RestController
@AllArgsConstructor
@RequestMapping("/quota")
@Api(value = "channel_quota_info_temp", description = "额度板块")
public class QuotaController {
    private ChannelRiskInfoService channelRiskInfoService;
    private ChannelQuotaInfoService channelQuotaInfoService;
    private ChannelUseCaseService channelUseCaseService;
    private ChannelConfig channelConfig;

    @Transactional
    @RequestMapping(value = "/upQuota", method = RequestMethod.POST)
    @ApiOperation(value = "保存数据")
    public IResponse saveAccountInfo(@RequestBody QuotaCondition condition) throws ParseException {
        if (condition.getRiskId() == null && condition.getRiskIdOld() == null) {
            return IResponse.fail("修改失败！");
        }
        Map<String, String> headers = new HashMap<String, String>();
        headers.put("clientId", channelConfig.getCaseClientId());
        headers.put("clientSecret", channelConfig.getCaseClientSecret());
        // 先看下进来的是新车还是二手车
        if (condition.getRiskId() != null) {
            ChannelQuotaInfoVo vo = new ChannelQuotaInfoVo();
            //如果有风控的新车id  就去判断  保证金调整是不是 0 如果是零  直接修改额度表。如果不是就要审核
            if (BigDecimal.ZERO.compareTo(condition.getMarginTune())==0) {
                ChannelRiskInfoTemp risk = channelRiskInfoService.getOne(Wrappers.<ChannelRiskInfoTemp>query().lambda().eq(ChannelRiskInfoTemp::getId, condition.getRiskId().toString()));
                //新车保证金调整金额赋值为0(实际保证金=数据库原始保证金+此次保证金调整金额；因为0所以 channelDeposit 不在重新赋值，将保证金调整金额赋值为0即可)
                risk.setMarginTune(BigDecimal.ZERO);
                channelRiskInfoService.updateById(risk);

                List<ChannelQuotaInfoTemp> list = new ArrayList<>();
                log.info("==================================渠道新车签放额度信息逻辑处理开始==================================》");
                //查询签放额度信息
                ChannelQuotaInfoTemp newQuota = channelQuotaInfoService.getById(condition.getQuotaId().toString());
                //临时额度赋值
                newQuota.setTempQuota(condition.getTempQuota());
                //签放额度赋值
                newQuota.setQuotaSigning(condition.getQuotaSigning());
                //查询数据库原始签放额度金额
                BigDecimal quotaAmount = newQuota.getQuotaAmount() == null ? BigDecimal.ZERO : newQuota.getQuotaAmount();
                //临时额度
                BigDecimal tempQuota = condition.getTempQuota() == null ? BigDecimal.ZERO : condition.getTempQuota();
                //当前签放额度=数据库已有签放额度+此次追加签放额度+临时额度
                newQuota.setQuotaAmount(quotaAmount.add(condition.getQuotaSigning()).add(tempQuota));
                //临时额度有效期
                newQuota.setValidityTermEnd(condition.getValidityTermEnd());
                channelQuotaInfoService.updateById(newQuota);
                list.add(newQuota);
                log.info("==================================渠道新车签放额度信息逻辑处理结束==================================》");

                log.info("==================================渠道新车先放后抵额度信息逻辑处理开始==================================》");
                //查询先放后抵额度信息
                ChannelQuotaInfoTemp newQuotaPut = channelQuotaInfoService.getById(condition.getQuotaIdPut().toString());
                //此次临时额度赋值
                newQuotaPut.setTempQuota(condition.getTempQuotaPut());
                //此次签放额度赋值
                newQuotaPut.setQuotaSigning(condition.getQuotaSigningPut());
                //临时额度
                BigDecimal tempQuotaPut = condition.getTempQuotaPut() == null ? BigDecimal.ZERO : condition.getTempQuotaPut();
                //获取数据原始先放后抵额度信息
                BigDecimal quotaAmountPut = newQuotaPut.getQuotaAmount() == null ? BigDecimal.ZERO : newQuotaPut.getQuotaAmount();
                //当前先放后抵额度=数据库已有先放额度额度+此次追加先放后抵额度+临时额度
                newQuotaPut.setQuotaAmount(quotaAmountPut.add(condition.getQuotaSigningPut()).add(tempQuotaPut));
                newQuotaPut.setValidityTermEnd(condition.getValidityTermEndPut());
                channelQuotaInfoService.updateById(newQuotaPut);
                list.add(newQuotaPut);
                log.info("==================================渠道新车先放后抵额度信息逻辑处理结束==================================》");

                log.info("==================================新车签放额度、先放后抵额度信息同步数据开始==================================》");
                vo.setQuota(list);
                vo.setRiskInfo(risk);
                channelUseCaseService.upQuota(vo,headers);
                log.info("==================================新车签放额度、先放后抵额度信息同步数据结束==================================》");
            } else {
                ChannelRiskInfoTemp risk = channelRiskInfoService.getOne(Wrappers.<ChannelRiskInfoTemp>query().lambda().eq(ChannelRiskInfoTemp::getId, condition.getRiskId().toString()));
                if (risk != null) {
                    //新车保证金调整金额赋值
                    risk.setMarginTune(condition.getMarginTune());
                    BigDecimal channelDeposit = risk.getChannelDeposit() == null ? BigDecimal.ZERO : risk.getChannelDeposit();
                    //最新保证金额=原始保证金+此次保证金调整金额
                    risk.setChannelDeposit(channelDeposit.add(condition.getMarginTune()));
                    channelRiskInfoService.updateById(risk);

                    List<ChannelQuotaInfoTemp> list = new ArrayList<>();
                    log.info("==================================渠道新车签放额度信息逻辑处理开始==================================》");
                    //查询签放额度信息
                    ChannelQuotaInfoTemp newQuota = channelQuotaInfoService.getById(condition.getQuotaId().toString());
                    //临时额度赋值
                    newQuota.setTempQuota(condition.getTempQuota());
                    //签放额度赋值
                    newQuota.setQuotaSigning(condition.getQuotaSigning());
                    //临时额度
                    BigDecimal tempQuota = condition.getTempQuota() == null ? BigDecimal.ZERO : condition.getTempQuota();
                    //查询数据库原始签放额度金额
                    BigDecimal quotaAmount = newQuota.getQuotaAmount() == null ? BigDecimal.ZERO : newQuota.getQuotaAmount();
                    //当前签放额度=数据库已有签放额度+此次追加签放额度+临时额度
                    newQuota.setQuotaAmount(quotaAmount.add(condition.getQuotaSigning()).add(tempQuota));
                    //临时额度有效期
                    newQuota.setValidityTermEnd(condition.getValidityTermEnd());
                    channelQuotaInfoService.updateById(newQuota);
                    list.add(newQuota);
                    log.info("==================================渠道新车签放额度信息逻辑处理结束==================================》");


                    log.info("==================================渠道新车先放后抵额度信息逻辑处理开始==================================》");
                    //查询先放后抵额度信息
                    ChannelQuotaInfoTemp newQuotaPut = channelQuotaInfoService.getById(condition.getQuotaIdPut().toString());
                    //此次临时额度赋值
                    newQuotaPut.setTempQuota(condition.getTempQuotaPut());
                    //此次签放额度赋值
                    newQuotaPut.setQuotaSigning(condition.getQuotaSigningPut());
                    //临时额度
                    BigDecimal tempQuotaPut = condition.getTempQuotaPut() == null ? BigDecimal.ZERO : condition.getTempQuotaPut();
                    //获取数据原始先放后抵额度信息
                    BigDecimal quotaAmountPut = newQuotaPut.getQuotaAmount() == null ? BigDecimal.ZERO : newQuotaPut.getQuotaAmount();
                    //当前先放后抵额度=数据库已有先放额度额度+此次追加先放后抵额度
                    newQuota.setQuotaAmount(quotaAmountPut.add(condition.getQuotaSigningPut()).add(tempQuotaPut));
                    newQuotaPut.setValidityTermEnd(condition.getValidityTermEndPut());
                    channelQuotaInfoService.updateById(newQuotaPut);
                    list.add(newQuotaPut);
                    log.info("==================================渠道新车先放后抵额度信息逻辑处理结束==================================》");

                    //审批流程结束之后调用（暂无审批流程,所以直接更新）
                    log.info("==================================新车签放额度、先放后抵额度信息同步数据开始==================================》");
                    vo.setQuota(list);
                    vo.setRiskInfo(risk);
                    channelUseCaseService.upQuota(vo,headers);
                    log.info("==================================新车签放额度、先放后抵额度信息同步数据结束==================================》");
                    //审批流程结束之后调用（暂无审批流程,所以直接更新）
                }
            }
        }
        //下面去判断这次有没有二手车
        if (condition.getRiskIdOld() != null) {
            ChannelQuotaInfoVo vo = new ChannelQuotaInfoVo();
            // 再去判断二手车 保证金调整
            if (BigDecimal.ZERO.compareTo(condition.getMarginTuneOld())==0) {
                ChannelRiskInfoTemp riskOld = channelRiskInfoService.getOne(Wrappers.<ChannelRiskInfoTemp>query().lambda().eq(ChannelRiskInfoTemp::getId, condition.getRiskIdOld()));
                //二手车保证金调整金额赋值为0(实际保证金=数据库原始保证金+此次保证金调整金额；因为0所以 channelDeposit 不在重新赋值，将保证金调整金额赋值为0即可)
                riskOld.setMarginTune(BigDecimal.ZERO);
                channelRiskInfoService.updateById(riskOld);

                List<ChannelQuotaInfoTemp> list = new ArrayList<>();
                log.info("==================================渠道二手车签放额度信息逻辑处理开始==================================》");
                //查询签放额度信息
                ChannelQuotaInfoTemp oldQuota = channelQuotaInfoService.getById(condition.getQuotaIdOld().toString());
                //临时额度赋值
                oldQuota.setTempQuota(condition.getTempQuotaOld());
                //签放额度赋值
                oldQuota.setQuotaSigning(condition.getQuotaSigningOld());
                //临时额度
                BigDecimal tempQuotaOld = condition.getTempQuotaOld() == null ? BigDecimal.ZERO : condition.getTempQuotaOld();
                //查询数据库原始签放额度金额
                BigDecimal quotaAmount = oldQuota.getQuotaAmount() == null ? BigDecimal.ZERO : oldQuota.getQuotaAmount();
                //当前签放额度=数据库已有签放额度+此次追加签放额度+临时额度
                oldQuota.setQuotaAmount(quotaAmount.add(condition.getQuotaSigningOld()).add(tempQuotaOld));
                //临时额度有效期
                oldQuota.setValidityTermEnd(condition.getValidityTermEndOld());
                channelQuotaInfoService.updateById(oldQuota);
                list.add(oldQuota);
                log.info("==================================渠道二手车签放额度信息逻辑处理结束==================================》");

                log.info("==================================渠道二手车先放后抵额度信息逻辑处理开始==================================》");
                //查询先放后抵额度信息
                ChannelQuotaInfoTemp oldQuotaPut = channelQuotaInfoService.getById(condition.getQuotaIdPutOld().toString());
                //此次临时额度赋值
                oldQuotaPut.setTempQuota(condition.getTempQuotaPutOld());
                //此次签放额度赋值
                oldQuotaPut.setQuotaSigning(condition.getQuotaSigningPutOld());
                //临时额度
                BigDecimal tempQuotaPutOld = condition.getTempQuotaPutOld() == null ? BigDecimal.ZERO : condition.getTempQuotaPutOld();
                //获取数据原始先放后抵额度信息
                BigDecimal quotaAmountPut = oldQuotaPut.getQuotaAmount() == null ? BigDecimal.ZERO : oldQuotaPut.getQuotaAmount();
                //当前先放后抵额度=数据库已有先放额度额度+此次追加先放后抵额度+临时额度
                oldQuotaPut.setQuotaAmount(quotaAmountPut.add(condition.getQuotaSigningPutOld()).add(tempQuotaPutOld));
                oldQuotaPut.setValidityTermEnd(condition.getValidityTermEndPutOld());
                channelQuotaInfoService.updateById(oldQuotaPut);
                list.add(oldQuotaPut);
                log.info("==================================渠道二手车先放后抵额度信息逻辑处理结束==================================》");

                log.info("==================================二手车签放额度、先放后抵额度信息同步数据开始==================================》");
                vo.setQuota(list);
                vo.setRiskInfo(riskOld);
                channelUseCaseService.upQuota(vo, headers);
                log.info("==================================二手车签放额度、先放后抵额度信息同步数据结束==================================》");
            } else {
                ChannelRiskInfoTemp riskOld = channelRiskInfoService.getOne(Wrappers.<ChannelRiskInfoTemp>query().lambda().eq(ChannelRiskInfoTemp::getId, condition.getRiskIdOld().toString()));
                if (riskOld != null) {
                    //二手车保证金调整金额赋值
                    riskOld.setMarginTune(condition.getMarginTuneOld());
                    //最新保证金额=原始保证金+此次保证金调整金额
                    BigDecimal channelDeposit = riskOld.getChannelDeposit() == null ? BigDecimal.ZERO : riskOld.getChannelDeposit();
                    riskOld.setChannelDeposit(channelDeposit.add(condition.getMarginTuneOld()));
                    channelRiskInfoService.updateById(riskOld);

                    List<ChannelQuotaInfoTemp> list = new ArrayList<>();
                    log.info("==================================渠道二手车签放额度信息逻辑处理开始==================================》");
                    //查询签放额度信息
                    ChannelQuotaInfoTemp oldQuota = channelQuotaInfoService.getById(condition.getQuotaIdOld().toString());
                    //临时额度赋值
                    oldQuota.setTempQuota(condition.getTempQuotaOld());
                    //签放额度赋值
                    oldQuota.setQuotaSigning(condition.getQuotaSigningOld());
                    //临时额度
                    BigDecimal tempQuotaOld = condition.getTempQuotaOld() == null ? BigDecimal.ZERO : condition.getTempQuotaOld();
                    //查询数据库原始签放额度金额
                    BigDecimal quotaAmount = oldQuota.getQuotaAmount() == null ? BigDecimal.ZERO : oldQuota.getQuotaAmount();
                    //当前签放额度=数据库已有签放额度+此次追加签放额度+临时额度
                    oldQuota.setQuotaAmount(quotaAmount.add(condition.getQuotaSigningOld()).add(tempQuotaOld));
                    //临时额度有效期
                    oldQuota.setValidityTermEnd(condition.getValidityTermEndOld());
                    channelQuotaInfoService.updateById(oldQuota);
                    list.add(oldQuota);
                    log.info("==================================渠道二手车签放额度信息逻辑处理结束==================================》");

                    log.info("==================================渠道二手车先放后抵额度信息逻辑处理开始==================================》");
                    //查询先放后抵额度信息
                    ChannelQuotaInfoTemp oldQuotaPut = channelQuotaInfoService.getById(condition.getQuotaIdPutOld().toString());
                    //此次临时额度赋值
                    oldQuotaPut.setTempQuota(condition.getTempQuotaPutOld());
                    //此次签放额度赋值
                    oldQuotaPut.setQuotaSigning(condition.getQuotaSigningPutOld());
                    //临时额度
                    BigDecimal tempQuotaPutOld = condition.getTempQuotaPutOld() == null ? BigDecimal.ZERO : condition.getTempQuotaPutOld();
                    //获取数据原始先放后抵额度信息
                    BigDecimal quotaAmountPut = oldQuotaPut.getQuotaAmount() == null ? BigDecimal.ZERO : oldQuotaPut.getQuotaAmount();
                    //当前先放后抵额度=数据库已有先放额度额度+此次追加先放后抵额度
                    oldQuotaPut.setQuotaAmount(quotaAmountPut.add(condition.getQuotaSigningPutOld()).add(tempQuotaPutOld));
                    oldQuotaPut.setValidityTermEnd(condition.getValidityTermEndPutOld());
                    channelQuotaInfoService.updateById(oldQuotaPut);
                    list.add(oldQuotaPut);
                    log.info("==================================渠道二手车先放后抵额度信息逻辑处理结束==================================》");

                    //审批流程结束之后调用（暂无审批流程,所以直接更新）
                    log.info("==================================二手车签放额度、先放后抵额度信息同步数据开始==================================》");
                    vo.setQuota(list);
                    vo.setRiskInfo(riskOld);
                    channelUseCaseService.upQuota(vo,headers);
                    log.info("==================================二手车签放额度、先放后抵额度信息同步数据结束==================================》");
                    //审批流程结束之后调用（暂无审批流程,所以直接更新）
                }
            }

        }

        return IResponse.success(Boolean.TRUE).setMsg("修改成功");
    }
}
